package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 *
 */
@Service
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Override
    public void add(AddressBook addressBook) {

        //补充属性，用户id
        addressBook.setUserId(BaseContext.getCurrentId());
        //设置非默认地址
        addressBook.setIsDefault(0);
        //保存到数据库
        addressBookMapper.add(addressBook);

    }

    /**
     * 查询当前登录用户的所有地址信息
     * @return
     */
    @Override
    public List<AddressBook> list() {
        AddressBook addressBook = new AddressBook();
        Long userId = BaseContext.getCurrentId();
        addressBook.setUserId(userId);
        List<AddressBook> list = addressBookMapper.list(addressBook);
        return list;
    }


    /**
     * 根据id查询地址
     * @param id
     * @return
     */
    @Override
    public AddressBook getById(Long id) {
        AddressBook addressBook = addressBookMapper.getById(id);
        return addressBook;
    }

    /**
     * 根据ID修改地址
     * @param addressBook
     */
    @Override
    public void update(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(0);
        addressBookMapper.update(addressBook);
    }

    /**
     * 修改默认地址
     * @param addressBook
     */
    @Override
    public void updateDefault(AddressBook addressBook) {
        //1. 将当前用户的所有地址修改为非默认地址sql:update address_book set is_default = 0 where user_id = ?
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(0);
        addressBookMapper.updateByIdDefault(addressBook);

        //2. 将当前地址修改为默认地址 sql:update address_book set is_default = 1 where id = ?
        addressBook.setIsDefault(1);
        addressBookMapper.update(addressBook);

    }

    /**
     * 查询默认地址
     * @param addressBook
     * @return
     */
    @Override
    public List<AddressBook> getDefault(AddressBook addressBook) {
        List<AddressBook> list = addressBookMapper.getDefault(addressBook);
        return list;
    }

    /**
     * 根据ID删除地址
     * @param id
     */
    @Override
    public void deleteById(Long id) {
        addressBookMapper.deleteById(id);
    }

}
